import React,{Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, SafeAreaView, Dimensions, Animated, Easing,PanResponder} from 'react-native'
import {Container,Header,Tab,Tabs,ScrollableTab,TabContainer,Button,CheckBox,List, ListItem,Icon, Separator,Content,Form, Item, Input, Label } from 'native-base'
import Carousel from 'react-native-snap-carousel'
import { ScrollView } from 'react-native-gesture-handler';
import {BoxShadow} from 'react-native-shadow'
import Icon1 from 'react-native-vector-icons/FontAwesome5';
import {storage} from '../utils/storage'
import SplashScreen from 'react-native-splash-screen';

const { width: viewportWidth, height: viewportHeight } = Dimensions.get('window');

function wp (percentage) {
    const value = (percentage * viewportWidth) / 100;
    return Math.round(value);
}

const slideHeight = viewportHeight * 0.36;
const slideWidth = wp(75);
const itemHorizontalMargin = wp(2);

export const sliderWidth = viewportWidth;
export const itemWidth = slideWidth + itemHorizontalMargin * 2;

export default class WelcomePage extends Component {

    //写变量的地方
    constructor(props) {
        super(props);
        this.state = {
            selectedTab: 'redTab',
            result: "测试",
            entries: [1, 2, 3, 4],
            animatedValue: new Animated.Value(0),
            scrollY: 0,
        }
        this.animating = false;
    }

    async componentDidMount() {
         this.splashTimer = setTimeout(()=>{SplashScreen.hide()}, 800);
        let token = await storage.load('token');
        if(ScreenUtil.isEmpty(token)) this.props.navigation.navigate("LoginSreen")
    }

    async componentWillMount() {
        const {navigation} = this.props;
        let isFirst = await storage.load('isFirst');
        if(!isFirst) {
            storage.save('isFirst',true)
            navigation.navigate('GuildPage')
        }
        this._panResponder = PanResponder.create({
            onMoveShouldSetPanResponderCapture:(evt, gestureState) => true,
            onPanResponderGrant: (evt, gestureState) => true,
            onPanResponderMove: (evt, gestureState) => true,
            onPanResponderRelease: (event, gestureState) => {
                // 我们只需要在这里判断 gestureState.dy 的值是否为正负
                if (gestureState.dy < 0) {
                    // 执行向上移动画
                    Animated.timing(this.state.animatedValue,{
                        toValue:-50,
                        duration: 400,
                        easing: Easing.in(Easing.ease)
                    }).start();
                }else {
                    Animated.timing(this.state.animatedValue,{
                        toValue:0,
                        duration: 400,
                        easing: Easing.in(Easing.ease)
                    }).start();
                }
            }
        })
    }

    componentWillUnmount() {
        // 如果存在this.timer，则使用clearTimeout清空。
        // 如果你使用多个timer，那么用多个变量，或者用个数组来保存引用，然后逐个clear
        this.timer && clearTimeout(this.timer);
        this.splashTimer && clearTimeout(this.splashTimer);
    }

    _onHandlerStateChange = (event)=> {
        console.log(66666)
    }

    _onGestureEvent = () => {
        return Animated.event(
            [],
            {useNativeDriver:true})
    }

    _onScroll = (event)=> {
        // console.log('[event]',event.nativeEvent.contentOffset.y)
        let eventY = event.nativeEvent.contentOffset.y
        // 我们只需要在这里判断 gestureState.dy 的值是否为正负
        // console.log('[this.animating]',this.state.animatedValue)
        if (this.state.scrollY - eventY < 0 && eventY > 0 && this.state.animatedValue._value === 0 && !this.animating) {
            // 执行向上移动画
            this.animating = true;
            Animated.timing(this.state.animatedValue,{
                toValue:-50,
                duration: 250,
                easing: Easing.in(Easing.ease)
            }).start((res)=>{
                this.timer = setTimeout(()=>{this.animating = false},150)
            });
        }else if(this.state.scrollY - eventY > 0 && eventY < 80 && this.state.animatedValue._value === -50  && !this.animating){
            this.animating = true;
            Animated.timing(this.state.animatedValue,{
                toValue:0,
                duration: 250,
                easing: Easing.in(Easing.ease)
            }).start((res)=>{
                this.timer = setTimeout(()=>{this.animating = false},150)
            });
        }
        // this.setState({scrollY:eventY})
    }

    _renderItem ({item, index}) {
        const shadowOpt = {
            width:itemWidth,
            height:ScreenUtil.scaleHeight(150),
            color:"#333",
            border:3,
            radius:5,
            opacity:0.3,
            x:0,
            y:1,
            style:{marginVertical:5}
        }
        return (
            <BoxShadow setting={shadowOpt}>
                <View style={styles.swiperItem}>
                    <Image resizeMode='stretch' style={styles.swiperImage} source={require('../assets/images/banner.jpg')} />
                </View>
            </BoxShadow>
        );
    }

    _renderScrollAnima = (e:Object)=> {
        let tempY = e.nativeEvent.contentOffset.y;
        console.log('[tempY]',tempY)
        console.log('[scrollY]',this.state.scrollY)
        if(this.state.scrollY > tempY ) {
            console.log('[start animated pull]')
            Animated.timing(this.state.animatedValue,{
                toValue:0,
                duration: 400,
                easing: Easing.in(Easing.ease)
            }).start();
        }else {
            console.log('[start animated push]')
            Animated.timing(this.state.animatedValue,{
                toValue:-50,
                duration: 400,
                easing: Easing.in(Easing.ease)
            }).start();
        }
    }

    _onScrollEndDrag = (e:Object)=> {
        console.log('[end drag]',e.nativeEvent.contentOffset.y)
        this.setState({scrollY:e.nativeEvent.contentOffset.y});
        // console.log('[onScrollEndDrag]',this.state.animatedValue)
    }

    //写页面的地方
    render() {
        return (
            //在这写页面！！！
            <View style={{ flex: 1, backgroundColor: '#f3f3f3' }}>
                <Animated.View style={{marginTop:this.state.animatedValue}}>
                    <Header style={styles.headSearch} searchBar rounded androidStatusBarColor={'pink'} >
                        <Item style={styles.searchItem} >
                            <Icon name="ios-search" />
                            <Input placeholder="Search" />
                            <Icon name="ios-people" />
                        </Item>
                    </Header>
                </Animated.View>
                <ScrollView
                    style={styles.scrollBox}
                    scrollEventThrottle={1}
                    // onScrollBeginDrag={this._renderScrollAnima}
                    onScrollEndDrag={this._onScrollEndDrag}
                    onScroll={this._onScroll}
                    // onGestureEvent={this._onGestureEvent}
                    // onHandlerStateChange={this._onHandlerStateChange}
                >
                    <View style={styles.swiperWrapper} >
                        <Carousel
                            style={styles.swiper}
                            ref={(c) => { this._carousel = c; }}
                            layout={'default'}
                            data={this.state.entries}
                            renderItem={this._renderItem}
                            sliderWidth={sliderWidth}
                            firstItem={1}
                            itemWidth={itemWidth}
                            autoplay
                            loop={true}
                        />
                    </View>
                    <ScrollView style={styles.scrollHoriz} horizontal showsHorizontalScrollIndicator={false} >
                        <View style={styles.scrolList}>
                            <Image style={styles.scrolListImg} source={require('../assets/images/categoryimg.jpg')} />
                            <Text style={styles.scrolListTit}>分类</Text>
                        </View>
                        <View style={styles.scrolList}>
                            <Image style={styles.scrolListImg} source={require('../assets/images/categoryimg1.jpg')} />
                            <Text style={styles.scrolListTit}>分类</Text>
                        </View>
                        <View style={styles.scrolList}>
                            <Image style={styles.scrolListImg} source={require('../assets/images/categoryimg0.jpg')} />
                            <Text style={styles.scrolListTit}>分类</Text>
                        </View>
                        <View style={styles.scrolList}>
                            <Image style={styles.scrolListImg} source={require('../assets/images/categoryimg.jpg')} />
                            <Text style={styles.scrolListTit}>分类</Text>
                        </View>
                        <View style={styles.scrolList}>
                            <Image style={styles.scrolListImg} source={require('../assets/images/categoryimg1.jpg')} />
                            <Text style={styles.scrolListTit}>分类</Text>
                        </View>
                        <View style={styles.scrolList}>
                            <Image style={styles.scrolListImg} source={require('../assets/images/categoryimg.jpg')} />
                            <Text style={styles.scrolListTit}>分类</Text>
                        </View>
                    </ScrollView>
                    <View style={styles.homeList}>
                        <View style={styles.homeTit}>
                            <Text style={styles.homeTit_tit}>推荐书籍</Text>
                            <Text style={styles.homeTit_more}>更多&gt;</Text>
                        </View>
                        <List style={styles.listbox}>
                            <ListItem style={styles.listItem}>
                                <Image style={styles.itemImg} source={require('../assets/images/shuimg.jpg')} />
                                <View style={styles.itemCon}>
                                    <Text style={styles.conTit}>童书是童书</Text>
                                    <Text style={styles.conInfo}>如何用童书给孩子讲故事？哪些童书可以帮孩子建立良好的的品格？哪些童书具有启发性</Text>
                                    <View style={styles.conBt}>
                                        <Text style={styles.gray}>黄乃宇</Text>
                                        <View style={styles.eye}>
                                            <Icon1 name='eye' solid size={10} color="#aaa" />
                                            <Text style={styles.gray}> 5820</Text>
                                        </View>
                                    </View>
                                </View>
                            </ListItem>
                            <ListItem style={styles.listItem}>
                                <Image style={styles.itemImg} source={require('../assets/images/shuimg1.jpg')} />
                                <View style={styles.itemCon}>
                                    <Text style={styles.conTit}>童书是童书</Text>
                                    <Text style={styles.conInfo}>如何用童书给孩子讲故事？哪些童书可以帮孩子建立良好的的品格？哪些童书具有启发性</Text>
                                    <View style={styles.conBt}>
                                        <Text style={styles.gray}>黄乃宇</Text>
                                        <View style={styles.eye}>
                                            <Icon1 name='eye' solid size={10} color="#aaa" />
                                            <Text style={styles.gray}> 5820</Text>
                                        </View>
                                    </View>
                                </View>
                            </ListItem>
                            <ListItem style={styles.listItem}>
                                <Image style={styles.itemImg} source={require('../assets/images/shuimg.jpg')} />
                                <View style={styles.itemCon}>
                                    <Text style={styles.conTit}>童书是童书</Text>
                                    <Text style={styles.conInfo}>如何用童书给孩子讲故事？哪些童书可以帮孩子建立良好的的品格？哪些童书具有启发性</Text>
                                    <View style={styles.conBt}>
                                        <Text style={styles.gray}>黄乃宇</Text>
                                        <View style={styles.eye}>
                                            <Icon1 name='eye' solid size={10} color="#aaa" />
                                            <Text style={styles.gray}> 5820</Text>
                                        </View>
                                    </View>
                                </View>
                            </ListItem>
                            <ListItem style={styles.listItem}>
                                <Image style={styles.itemImg} source={require('../assets/images/shuimg.jpg')} />
                                <View style={styles.itemCon}>
                                    <Text style={styles.conTit}>童书是童书</Text>
                                    <Text style={styles.conInfo}>如何用童书给孩子讲故事？哪些童书可以帮孩子建立良好的的品格？哪些童书具有启发性</Text>
                                    <View style={styles.conBt}>
                                        <Text style={styles.gray}>黄乃宇</Text>
                                        <View style={styles.eye}>
                                            <Icon1 name='eye' solid size={10} color="#aaa" />
                                            <Text style={styles.gray}> 5820</Text>
                                        </View>
                                    </View>
                                </View>
                            </ListItem>
                            <ListItem style={styles.listItem}>
                                <Image style={styles.itemImg} source={require('../assets/images/shuimg.jpg')} />
                                <View style={styles.itemCon}>
                                    <Text style={styles.conTit}>童书是童书</Text>
                                    <Text style={styles.conInfo}>如何用童书给孩子讲故事？哪些童书可以帮孩子建立良好的的品格？哪些童书具有启发性</Text>
                                    <View style={styles.conBt}>
                                        <Text style={styles.gray}>黄乃宇</Text>
                                        <View style={styles.eye}>
                                            <Icon1 name='eye' solid size={10} color="#aaa" />
                                            <Text style={styles.gray}> 5820</Text>
                                        </View>
                                    </View>
                                </View>
                            </ListItem>
                        </List>
                    </View>
                </ScrollView>
            </View>
        )
    }


}

//写样式的地方，只在这写样式，该怎么写就怎么写
const styles = StyleSheet.create({
    headSearch:{
        marginTop:0,
        backgroundColor:'pink',

    },
    searchItem:{
        backgroundColor:'#eee',
        borderRadius:100,
    },
    scrollBox:{
        flex:1,
    },
    swiperWrapper:{
        height:ScreenUtil.scaleHeight(160),
        backgroundColor:'#fff',
    },
    swiper: {
    },
    swiperItem: {
        height:ScreenUtil.scaleHeight(150),
        borderRadius:5,
        overflow:'hidden',
        flex:1,
        justifyContent:'center',
        alignItems: 'center',
    },
    swiperImage:{
        width:itemWidth,
    },
    scrollHoriz:{
        paddingTop:5,
        paddingBottom:10,
        backgroundColor:'#fff',
    },
    scrolList:{
        flex:1,
        margin:ScreenUtil.scaleHeight(6),
        width:ScreenUtil.scaleHeight(80),
        height:ScreenUtil.scaleHeight(80),
        position:'relative',
        backgroundColor:'#000',
        overflow:'hidden',
        borderRadius:5,
        justifyContent:'center',
        alignItems: 'center',
    },
    scrolListImg:{
        opacity:0.5,
    },
    scrolListTit:{
        position:'absolute',
        fontSize:16,
        color:'#fff',
        zIndex:10,
    },
    homeList:{
        marginTop:10,
        backgroundColor:'#fff',
        padding:15,
    },
    homeTit:{
        flexDirection:'row',
        justifyContent:'space-between'
    },
    homeTit_tit:{
        fontSize:16,
        color:'#333',
    },
    listbox:{
        flex:1,
        overflow:'hidden',
    },
    listItem:{
        flex:1,
        overflow:'hidden',
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'flex-start',
        marginLeft:0,
        marginRight:-10,
        borderBottomWidth:0,
        paddingBottom:5,
    },
    itemImg:{
        width:80,
        height:110,
    },
    itemCon:{
        flex:1,
        marginLeft:10,
    },
    conTit:{
        fontSize:16,
        color:'#333',

    },
    conInfo:{
        fontSize:12,
        color:'#999',
        lineHeight:16,
        marginTop:10,
    },
    conBt:{
        fontSize:12,
        color:'#999',
        marginTop:10,
        flexDirection:'row',
        justifyContent:'space-between',
    },
    gray:{
        color:'#999',
        fontSize:12,
    },
    eye:{
        flexDirection:'row',
        justifyContent:'flex-end',
        alignItems:'center',
    },
})